package com.impetus.project.skilltest.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.impetus.project.skilltest.core.SkillTestException;
import com.impetus.project.skilltest.dataobject.ObjectiveQuestion;
import com.impetus.project.skilltest.util.HibernateUtil;

public class ObjectiveQuestionDAO {
	private static Logger logger = Logger.getLogger(ObjectiveQuestionDAO.class.getName());
	
	private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
	
	@SuppressWarnings("unchecked")
	public static List<ObjectiveQuestion> getObjectiveQuestionById ( String objectiveQuestionId )
	throws SkillTestException
	{
		List<ObjectiveQuestion> objectiveQuestionList = new ArrayList<ObjectiveQuestion>();
		
		try{
			objectiveQuestionList = sessionFactory.getCurrentSession()
			.createCriteria(ObjectiveQuestion.class)
			.add(Restrictions.like("QUESTION_ID", objectiveQuestionId))
			.list();
		}catch(Exception e)
		{
			logger.log(Level.INFO, e.getMessage());
			throw new SkillTestException(e);
		}
		
		return objectiveQuestionList;
	}
	
	@SuppressWarnings("unchecked")
	public static List<ObjectiveQuestion> getObjectiveQuestionList ( String domain, String complexity, int count )
	throws SkillTestException
	{
		List<ObjectiveQuestion> objectiveQuestionList = new ArrayList<ObjectiveQuestion>();
		
		try{
			objectiveQuestionList = sessionFactory.getCurrentSession()
			.createCriteria(ObjectiveQuestion.class)
			.add(Restrictions.like("Q_DOMAIN", domain))
			.add(Restrictions.like("COMPLEXITY", complexity))
			.add(Restrictions.like("IS_ENABLED", "Y"))
			.add(Restrictions.eq("limit", count))
			.addOrder(Order.asc("RAND()"))
			.list();
		}catch(Exception e)
		{
			logger.log(Level.INFO, e.getMessage());
			throw new SkillTestException(e);
		}
		
		
		return objectiveQuestionList;
		
	}
	public static void saveUpdateObjectiveQuestion(ObjectiveQuestion objectiveQuestion)
	throws SkillTestException
	{
		try
		{
			sessionFactory.getCurrentSession().saveOrUpdate(objectiveQuestion);
		
		}catch(Exception e)
		{
			logger.log(Level.INFO, e.getMessage());
			throw new SkillTestException(e);
		}
	}	
	
	public static void deleteObjectiveQuestion(ObjectiveQuestion objectiveQuestion)
	throws SkillTestException
	{
		try
		{
			sessionFactory.getCurrentSession().delete(objectiveQuestion);
			
		}catch(Exception e)
		{
			logger.log(Level.INFO, e.getMessage());
			throw new SkillTestException(e);
		}
	}
}
